<?php
/**
 *
 * @author ninetyseven.
 * @date 2023-03-27 22:52
 */

namespace App\Services;

use App\Enum\CommitteeMemberEnum;
use App\Enum\OrderEnum;
use App\Enum\TravelEnum;
use App\Enum\VehicleExceptionEnum;
use App\Enum\VillagerEnum;
use App\Models\ActivityModel;
use App\Models\CommitteeMemberModel;
use App\Models\CommitteeSubAccountModel;
use App\Models\DriverModel;
use App\Models\OrderModel;
use App\Models\UserCommunityModel;
use App\Models\VehicleExceptionModel;
use App\Models\VillagerUserCommunityModel;
use App\Models\VillagerUserModel;
use App\Services\Tools\HelpService;
use Illuminate\Support\Facades\DB;

class VillageCommitteeService extends BaseService
{
    /**
     * 村委会审核
     * @param array $params
     * @return bool
     * @throws \Exception
     * @author ninetyseven.
     * @date 2023-04-17 23:42
     */
    public static function stateSave(array $params = []): bool
    {
        $communityName = $params['community_name'] ?? '';
        $communityAddress = $params['community_address'] ?? '';
        $communityImages = $params['community_images'] ?? '';
        $position = $params['position'] ?? '';
        $userId = request()->userId;

        if (empty($communityName)) {
            throw new \Exception('社区名称不存在');
        }
        if (empty($communityAddress)) {
            throw new \Exception('社区地址不存在');
        }
        if (empty($communityImages)) {
            throw new \Exception('社区图片不存在');
        }
        if (empty($position)) {
            throw new \Exception('职位不存在');
        }

        $obj = new CommitteeMemberModel();
        $obj->name = $communityName;
        $obj->address = $communityAddress;
        $obj->picture = $communityImages;
        $obj->position = $position;
        $obj->belonging_type = CommitteeMemberEnum::VILLAGER_TYPE;
        $obj->status = CommitteeMemberEnum::STATE_STATUS_WAIT;
        $obj->user_id = $userId;
        if (!$obj->save()) {
            throw new \Exception('绑定不存在');
        }
        return true;
    }

    /**
     * 预警订单列表
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public static function waringOrderList(): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        $where = [];
        $where[] = ['is_warning', '=', OrderEnum::ORDER_WARNING_YES];
        $where[] = ['status', '=', OrderEnum::STATUS_DRIVING];

        return OrderModel::query()
            ->where($where)
            ->paginate(HelpService::perPage());
    }

    /**
     * 预警订单详情
     * @param int $orderId
     * @return array
     * @throws \Exception
     */
    public static function waringOrderDetail(int $orderId = 0): array
    {
        $where = [];
        $where[] = ['is_warning', '=', OrderEnum::ORDER_WARNING_YES];
        $where[] = ['status', '=', OrderEnum::STATUS_DRIVING];
        $where[] = ['id', '=', $orderId];

        $info = OrderModel::query()
            ->where($where)
            ->first();
        if (!$info) {
            throw new \Exception('订单不存在');
        }

        return $info->toArray();
    }

    /**
     * 志愿者分配列表
     * @param $search
     * @return array
     */
    public static function volunteersList($search): array
    {
        $where = [];
        if (!empty($search)) {
            $where[] = ['real_name', 'like', '%' . $search . '%'];
        }
        $communityId = CommonService::getCommunity()['community_id'];

        $where[] = ['user_type', '=', TravelEnum::PLATFORM_VOLUNTEER];
        $where[] = ['community_id', '=', $communityId];
        $where[] = ['user_community.status', '=', 1];

        $result = UserCommunityModel::query()
            ->leftJoin('user','user.id','=','user_community.user_id')
            ->select()
            ->where($where)
            ->get();
        if (!$result) {
            return [];
        }

        foreach ($result as &$item){
            $item->account_name = !empty($item['nick_name']) ? $item['nick_name'] : '';
            $item->volunteers_status = $item->order_id ? OrderEnum::ORDER_VOLUNTEER_YES : OrderEnum::ORDER_VOLUNTEER_NO;
            $item->volunteers_status_name = $item->order_id ? OrderEnum::ORDER_VOLUNTEER_NAME[OrderEnum::ORDER_VOLUNTEER_YES] : OrderEnum::ORDER_VOLUNTEER_NAME[OrderEnum::ORDER_VOLUNTEER_NO] ;
        }
        unset($item);
        return $result->toArray();
    }

    /**
     * 志愿者分配
     * @param int $orderId
     * @param int $userId
     * @return true
     * @throws \Exception
     */
    public static function volunteersAdd(int $orderId = 0, int $userId = 0): bool
    {
        if ($orderId <= 0 || $userId <= 0) {
            throw new \Exception('参数错误');
        }

        $orderInfo = OrderModel::query()
            ->where('id', $orderId)
            ->first();
        if (!$orderInfo) {
            throw new \Exception('订单不存在');
        }

        //订单状态不是待接单或待出行时，不允许分配志愿者
        if (!in_array($orderInfo->status, [OrderEnum::STATUS_PENDING_ORDER, OrderEnum::STATUS_PENDING_TRAVEL])) {
            throw new \Exception('订单状态不允许分配志愿者');
        }

        if ($orderInfo->is_accompany != OrderEnum::ORDER_ACCOMPANY) {
            throw new \Exception('订单不属于陪同订单，不需要分配志愿者');
        }

        $userInfo = VillagerUserModel::query()
            ->where('id', $userId)
            ->first();
        if (!$userInfo) {
            throw new \Exception('用户不存在');
        }

        $orderInfo->volunteer_id = $userInfo->id;
        if (!$orderInfo->save()) {
            throw new \Exception('分配失败');
        }

        return true;
    }

    /**
     * 添加子账户
     * @param array $params
     * @return bool
     * @throws \Exception
     */
    public static function accountAdd(array $params = []): bool
    {
        $userId = $params['user_id'] ?? '';
        $type = $params['type'] ?? '';
        $name = $params['name'] ?? '';
        $phone = $params['phone'] ?? '';
        $idNumber = $params['id_number'] ?? '';
        $residentialAddress = $params['residential_address'] ?? '';
        $userType = self::getPlatformId();

        if (empty($userId)) {
            throw new \Exception('用户不存在');
        }
        if (empty($type)) {
            throw new \Exception('类型不存在');
        }
        if (empty($name)) {
            throw new \Exception('姓名不存在');
        }
        if (empty($phone)) {
            throw new \Exception('手机号不存在');
        }
        if (empty($idNumber)) {
            throw new \Exception('身份证号不存在');
        }
        if (empty($residentialAddress)) {
            throw new \Exception('居住地址不存在');
        }

        $obj = new CommitteeSubAccountModel();
        $obj->user_id = $userId;
        $obj->type = $type;
        $obj->committee_type = $userType;
        $obj->committee_id = request()->userId;
        $obj->account_name = $name;
        $obj->phone = $phone;
        $obj->id_number = $idNumber;
        $obj->residential_address = $residentialAddress;
        if (!$obj->save()) {
            throw new \Exception('添加失败');
        }

        if ($type == 1) {
            $type = TravelEnum::PLATFORM_VOLUNTEER;
        } else {
            $type = $userType;
        }

        $communityId = CommonService::getCommunity()['community_id'];
        $addCommunity = [
            'user_id' => $userId,
            'user_type' => $type,
            'community_id' => $communityId,
        ];

        if (!UserCommunityModel::query()->insert($addCommunity)) {
            throw new \Exception('添加失败');
        }

        DB::commit();
        return true;
    }

    /**
     * 获取子账户列表
     * getAccountList
     * @param string $search
     * @return array
     * @author ninetyseven.
     * @date 2023/5/3
     */
    public static function getAccountList(string $search = ''): array
    {
        $where = [];
        if (!empty($search)) {
            $where[] = ['account_name', 'like', '%' . $search . '%'];
        }

        return CommitteeSubAccountModel::query()
            ->select()
            ->where($where)
            ->get()->toArray();
    }

    /**
     * 获取子账户详情
     * @param int $id
     * @return array
     * @throws \Exception
     */
    public static function getAccountDetail(int $id = 0): array
    {
        if ($id <= 0) {
            throw new \Exception('参数错误');
        }

        $res = CommitteeSubAccountModel::query()
            ->select()
            ->where('id', $id)
            ->first();
        if (!$res) {
            throw new \Exception('数据不存在');
        }

        return $res->toArray();
    }

    /**
     * 删除子账户
     * @param int $id
     * @return bool
     * @throws \Exception
     */
    public static function accountDelete(int $id = 0): bool
    {
        if ($id <= 0) {
            throw new \Exception('参数错误');
        }

        $res = CommitteeSubAccountModel::query()
            ->where('id', $id)
            ->delete();
        if (!$res) {
            throw new \Exception('删除失败');
        }

        return true;
    }

    /**
     * 志愿者统计
     * volunteersStatistics
     * @author ninetyseven.
     * @date 2023/5/26
     */
    public static function volunteersStatistics(): array
    {
        //获取当前用户所在社区
        $communityId = CommonService::getCommunity()['community_id'];
        //获取当前社区下的志愿者
        $volunteer = UserCommunityModel::query()
            ->where('community_id', $communityId)
            ->where('user_type', TravelEnum::PLATFORM_VILLAGER)
            ->count();
        //获取当前社区下的村民
        $villager = UserCommunityModel::query()
            ->where('community_id', $communityId)
            ->where('user_type', TravelEnum::PLATFORM_VOLUNTEER)
            ->count();
        //获取当前用户所在社区发布的活动
        $activity = ActivityModel::query()
            ->where('community_id', $communityId)
            ->count();

        return [
            'beneficiary_count' => $volunteer,
            'volunteer_count' => $villager,
            'activity_count' => $activity,
        ];
    }

    /**
     * 异常上报
     * @throws \Exception
     * @author ninetyseven.
     * @date 2023-04-02 15:58
     */
    public function addAbnormal(array $params = []): bool
    {
        if (empty($params['reason'])) {
            throw new \Exception('故障原因不能为空');
        }

        if (count($params['images']) > VehicleExceptionEnum::IMAGE_COUNT) {
            throw new \Exception('图片上传张数超过限制');
        }

        $userId = \request()->userId;
        $platformId = self::getPlatformId();
        if ($platformId == TravelEnum::PLATFORM_DRIVER) {
            $info = DriverModel::query()->where('id', $userId)->select('car_plate_number')->first();
        } else {
            $info = VillagerUserModel::query()->where('id', $userId)->select()->first();
        }

        if (!$info) {
            throw new \Exception('用户信息不存在');
        }

        $addData = [
            'license_plate' => isset($info['car_plate_number']) ? $info['car_plate_number'] : '',
            'user_id' => $userId,
            // 1-司机 2-用户
            'user_type' => $platformId == TravelEnum::PLATFORM_DRIVER ? 1 : 2,
            'reason' => $params['reason'],
            'image' => is_array($params['images']) ? implode(',', $params['images']) : '',
        ];

        $res = VehicleExceptionModel::query()->create($addData);
        if (!$res) {
            throw new \Exception('异常上报失败');
        }

        return true;
    }
}
